package com.fast.fastenjoy.components.common.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fast.fastenjoy.base.manager.CacheEntityManager;
import com.fast.fastenjoy.base.manager.DataTranslationProvider;
import com.fast.fastenjoy.base.manager.SelectDataProvider;
import com.fast.fastenjoy.components.common.domain.BasicData;
import com.fast.fastenjoy.test.server.WeatherTest;

/**
 * 基础数据管理(缓存式)
 * @author chenliaohua
 *
 */
@Service("basicDataManager")
public class BasicDataManager extends CacheEntityManager<BasicData> implements SelectDataProvider<BasicData>, DataTranslationProvider{

	private static final String BASIC_DATA_OF_TYPE = "BASIC_DATA_OF_TYPE";
	
	public List<BasicData> getBasicData(String dataTypeCode){
		
		Map<String, List<BasicData>> allBasicData = getAllBasicData();
		
		return allBasicData != null ? allBasicData.get(dataTypeCode) : null;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, List<BasicData>> getAllBasicData(){
		
		return (Map<String, List<BasicData>>)getCache(BASIC_DATA_OF_TYPE);
	}
	
	@Override
	public void refCache() {
		
//		initChinaWeatherCityCodeData();
		
		List<BasicData> allBasicData = getAll();
		
		if(allBasicData != null){
			
			Map<String, List<BasicData>> _cache = new HashMap<String, List<BasicData>>();
			
			for(BasicData bd : allBasicData){
				if(bd != null){
					
					String dataTypeCode = bd.getDataTypeCode();
					
					List<BasicData> _tempList = _cache.get(dataTypeCode);
					
					if(_tempList == null){
						_tempList = new ArrayList<BasicData>();
					}
					
					_tempList.add(bd);
					
					_cache.put(dataTypeCode, _tempList);
				}
			}
			
			cache(BASIC_DATA_OF_TYPE, _cache);
		}
	}
	
	public void initChinaWeatherCityCodeData(){
		
		System.out.println("开始初始化天气城市编码数据");
		try {
			baseDao.executeByHql("delete from BasicData where dataTypeCode = 'WEATHER_CITY_CODE'", null);
			List<BasicData> testList = WeatherTest.getChinaWeatherCityCodeList();
			System.out.println("获取天气城市编码数据完毕，共" + testList.size() + "条数据!");
			baseDao.batchSave(testList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("初始化天气城市编码数据结束");
	}

	public String getValue(JSONObject json) {
		return null;
	}

	public List<BasicData> loadData(JSONObject json) {
		
		String dataTypeCode = json.getString("dataTypeCode");
		
		return getBasicData(dataTypeCode);
	}
	
}
